<template>
  <div class="app-container home">
    <!-- 统计图表卡片 -->
    <el-card class="stat-card">
      <div class="stat-title">文章类别数据统计</div>
      <div class="stat-charts-simple">
        <div class="stat-chart-item">
          <div class="stat-chart-title">点击量（柱状图）</div>
          <div ref="clickBarChart" class="stat-echart"></div>
        </div>
        <div class="stat-chart-item">
          <div class="stat-chart-title">评论量（折线图）</div>
          <div ref="commentLineChart" class="stat-echart"></div>
        </div>
        <div class="stat-chart-item">
          <div class="stat-chart-title">文章数量（饼图）</div>
          <div ref="countPieChart" class="stat-echart"></div>
        </div>
      </div>
    </el-card>
    <el-row :gutter="32" class="category-row">
      <el-col :span="8" v-for="(category, idx) in categoryList" :key="category.categoryId" class="category-col">
        <el-card shadow="hover" class="category-card">
          <div slot="header" class="card-header">
            <div class="category-title-container">
              <span class="category-title">{{ category.categoryName }}</span>
              <el-tag v-if="category.articleCount" :type="getRandomTagType()" size="mini" class="article-count-tag">
                {{ category.articleCount }} 篇文章
              </el-tag>
            </div>
            <el-button
              v-if="category.articleCount > 0"
              type="primary"
              size="mini"
              round
              @click="toggleExpand(idx)"
              class="expand-btn"
            >
              <i :class="category.expanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" style="margin-right: 4px" />
              <span>{{ category.expanded ? '收起' : '展开' }}</span>
            </el-button>
          </div>
          <el-collapse-transition>
            <div v-show="category.expanded" class="category-content-area">
              <el-table
                :data="category.articles"
                class="article-table"
                border
                size="mini"
                :show-header="true"
                :cell-style="{ padding: '4px 8px' }"
              >
                <el-table-column label="标题" prop="title" width="180">
                  <template slot-scope="scope">
                    <a
                      :href="`/article/article/detail/${scope.row.articleId}`"
                      target="_blank"
                      class="article-link"
                     
                    >
                      {{ scope.row.title }}
                    </a>
                  </template>
                </el-table-column>
                <el-table-column label="点击量" prop="clickCount" width="90">
                  <template slot-scope="scope">
                    <span class="click-count">
                      <i class="el-icon-view" style="margin-right: 2px; color: #F56C6C" />
                      {{ scope.row.clickCount }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="评论数" width="90">
                  <template slot-scope="scope">
                    <span class="comment-count">
                      <i class="el-icon-chat-dot-round" style="margin-right: 2px; color: #67C23A" />
                      {{ scope.row.commentCount || 0 }}
                    </span>
                  </template>
                </el-table-column>
            
              </el-table>
              <div v-if="category.articles.length === 0" class="empty-tips">
                <el-image
                  src="https://shadow.elemecdn.com/app/element/hfpen@ legacy.9-cf7.png"
                  fit="contain"
                  style="width: 80px; height: 80px; opacity: 0.5"
                />
                <p>暂无文章</p>
              </div>
            </div>
          </el-collapse-transition>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listCategory } from '@/api/category/category'
import { listByCategoryId } from '@/api/article/article'
import * as echarts from 'echarts'

export default {
  name: "Index",
  data() {
    return {
      categoryList: []
    }
  },
  created() {
    this.loadCategoryAndArticles()
  },
  methods: {
    async loadCategoryAndArticles() {
      const categoryRes = await listCategory()
      const categories = categoryRes.rows || []
      for (const cat of categories) {
        const articleRes = await listByCategoryId(cat.categoryId)
        cat.articles = articleRes.rows || []
        cat.expanded = false // 如果有文章就默认展开
        cat.articleCount = cat.articles.length
        // 统计点击量和评论量
        cat.clickCount = cat.articles.reduce((sum, a) => sum + (a.clickCount || 0), 0)
        cat.commentCount = cat.articles.reduce((sum, a) => sum + (a.commentCount || 0), 0)
      }
      this.categoryList = categories
      this.$nextTick(() => {
        this.renderCharts()
      })
    },
    goArticleDetail(articleId) {
      this.$router.push({ path: `/article/detail/${articleId}` })
    },
    toggleExpand(idx) {
      this.$set(this.categoryList[idx], 'expanded', !this.categoryList[idx].expanded)
    },
    getRandomTagType() {
      const types = ['success', 'info', 'warning', 'danger']
      return types[Math.floor(Math.random() * types.length)]
    },
    renderCharts() {
      // 数据准备
      const names = this.categoryList.map(cat => cat.categoryName)
      // 点击量
      const clickData = this.categoryList.map(cat => cat.clickCount)
      // 评论量
      const commentData = this.categoryList.map(cat => cat.commentCount)
      // 文章数量
      const countData = this.categoryList.map(cat => cat.articleCount)
      // 饼图数据
      const countPie = this.categoryList.map(cat => ({ name: cat.categoryName, value: cat.articleCount }))
      // 点击量-柱状图
      echarts.init(this.$refs.clickBarChart).setOption({
        tooltip: {},
        xAxis: { type: 'category', data: names },
        yAxis: { type: 'value' },
        series: [{ data: clickData, type: 'bar', name: '点击量', itemStyle: { color: '#409EFF' } }]
      })
      // 评论量-折线图
      echarts.init(this.$refs.commentLineChart).setOption({
        tooltip: {},
        xAxis: { type: 'category', data: names },
        yAxis: { type: 'value' },
        series: [{ data: commentData, type: 'line', name: '评论量', itemStyle: { color: '#F56C6C' }, lineStyle: { color: '#F56C6C' } }]
      })
      // 文章数量-饼图
      echarts.init(this.$refs.countPieChart).setOption({
        tooltip: { trigger: 'item' },
        legend: { top: 'bottom' },
        series: [{ name: '文章数量', type: 'pie', radius: ['40%', '70%'], avoidLabelOverlap: false, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: 16, fontWeight: 'bold' } }, labelLine: { show: false }, data: countPie }]
      })
    }
  }
}
</script>

<style scoped>
.home {
  padding: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #eaf0fa 100%);
  min-height: 100vh;
}

.category-row {
  margin-top: 20px;
}

.category-col {
  margin-bottom: 24px;
}

.category-card {
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.15);
  transition: all 0.3s;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.category-card:hover {
  box-shadow: 0 12px 32px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
}

.category-title-container {
  display: flex;
  align-items: center;
}

.category-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-right: 10px;
}

.article-count-tag {
  height: 24px;
  line-height: 24px;
  font-size: 12px;
}

.expand-btn {
  margin-left: 10px;
}

.category-content-area {
  padding: 16px;
  flex: 1;
  overflow: hidden;
}

.article-table {
  width: 100%;
  background-color: transparent;
  margin-bottom: 10px;
}

.article-link {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.article-link:hover {
  color: #66B1FF;
}

.click-count, .comment-count {
  font-size: 13px;
  display: flex;
  align-items: center;
}

.empty-tips {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  padding: 20px;
}

.stat-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(64,158,255,0.08);
  padding: 18px 24px 12px 24px;
}
.stat-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 12px;
}
.stat-charts-simple {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  justify-content: space-between;
}
.stat-chart-item {
  flex: 1 1 0;
  min-width: 420px;
  max-width: 540px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.stat-chart-title {
  font-size: 15px;
  color: #666;
  margin-bottom: 8px;
}
.stat-echart {
  width: 400px;
  height: 300px;
}
@media (max-width: 1200px) {
  .category-col {
    flex: 1 1 100%;
    min-width: 280px;
  }
  
  .category-row {
    margin-top: 16px;
  }
  .stat-charts-simple {
    flex-direction: column;
    gap: 12px;
  }
  .stat-chart-item {
    max-width: 100%;
    min-width: 0;
  }
  .stat-echart {
    width: 100%;
    min-width: 120px;
    height: 180px;
  }
}
</style>